<!-- MyComponent.vue -->
<template>
  <div>
    <h3>toRefs 嵌套属性示例</h3>
    <h4>{{ state }}</h4>
    <p>姓名：{{ name }}</p>
    <p>年龄：{{ age }}</p>
    <p>城市：{{ city }}</p>
    <button @click="updateInfo">更新信息</button>
    <button @click="addExclamation">姓名增加</button>
    <button @click="age++">年龄增加</button>

    <h3>{{ aa }}</h3>
    <h3>{{ bb }}</h3>
  </div>
</template>

<script setup>
import { reactive, toRefs } from 'vue'

// 1. 定义一个包含嵌套属性的响应式对象
const state = reactive({
  user: {
    name: 'Alice',
    age: 25,
    address: {
      city: 'Shanghai'
    }
  }
})
let car = reactive({ aa: 'benz', bb: 30 })
let { aa, bb } = { ...toRefs(car) }

// 2. 使用 toRefs 将嵌套属性转为响应式引用,解构赋值
const { name, age } = toRefs(state.user)
const { city } = toRefs(state.user.address)

// 3. 事件处理函数
function updateInfo() {
  name.value = 'Bob'
  age.value = 30
  city.value = 'Beijing'
}

// 新增：姓名增加按钮事件
function addExclamation() {
  name.value += '!'
}
</script>

<style scoped>
button {
  margin-top: 8px;
  margin-right: 8px;
}
</style>